<div id="formDiv"></div>
<script type="text/html" id="formContent">
  <form lay-filter="purchasePlanFormContent" id="purchasePlanFormContent" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div class="layui-form-item layui-row">
          <input name="id" type="hidden" />
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">采购类型</label>
            <div class="layui-input-block">
              <select id="purTypeId" name="purTypeId" lay-filter="purTypeId"></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">紧急程度</label>
            <div class="layui-input-block">
              <select id="purchaseUrgencyId" name="purchaseUrgencyId" lay-filter="purchaseUrgencyId"></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">计划到货时间</label>
            <div class="layui-input-block">
              <input type="text" class="layui-input" placeholder="计划到货时间" id="planOnTime" name="planOnTime" />
            </div>
          </div>
        </div>
        <div class="layui-form-item layui-row">
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">申请人</label>
            <div class="layui-input-block">
              <input type="text" class="layui-input adv-disable" id="creatorName" disabled name="creatorName" />
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label ">申报部门</label>
            <div class="layui-input-block">
              <select id="departmentId" name="departmentId" class="adv-disable" disabled lay-filter="departmentId"></select>
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">审核岗位</label>
            <div class="layui-input-block">
              <input type="text" class="layui-input adv-disable" id="postName" disabled name="postName" />
            </div>
          </div>
          <div class="layui-inline layui-col-md3">
            <label class="layui-form-label">订单审核人</label>
            <div class="layui-input-block">
              <select id="auditor" name="auditor" lay-filter="auditor"></select>
            </div>
          </div>
        </div>
        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <button class="layui-btn" type="button" id="Configure">配置采购物资</button>
          <!-- {{# } }} -->
          <table class="layui-table" id="purchasePlanFormTable" lay-filter="purchasePlanFormTable"></table>
        </div>
        <div class="layui-form-item layui-row" id="reasonInput">
          <div class="layui-inline layui-col-md6">
            <label class="layui-form-label">审核结果</label>
            <div class="layui-input-block">
              <input type="text" class="layui-input adv-disable" id="reason" name="reason" />
            </div>
          </div>
        </div>
        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" lay-filter="inquiryOrderInformationSubmit" type="button" lay-submit>提交</button>
          {{# if(d.eventName=='audit'){ }}
          <button class="layui-btn" type="button" id="purchasePlanSuccess">通过</button>
          <button class="layui-btn" type="button" id="purchasePlanFail">驳回</button>
          {{# } }}
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchasePlanFormTableBar">
  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>
<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = { ...parentData };

    let data = nowData?.data;
    laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
      $("#formDiv").after(html);
    });
    if (nowData.eventName === "detail") {
      admin.setFormDisable("#purchasePlanFormContent", true);
    }
    $("#reasonInput").hide();
    if (nowData.eventName === "audit") {
      $("#reason").val("");
      $("#Configure").hide();
      admin.setFormDisable("#purchasePlanFormContent", true);
      $("#reasonInput").show();
    }
    if (nowData.eventName === "edit") {
      $("#reasonInput").show();
      $("#reason").prop("disabled", true);
    }
    await admin.initDataSelectPro(
      "user/admin/role/list",
      {
        limit: 99999,
        isProduce: 1
      },
      "departmentId",
      "部门",
      null
    );

    await admin.initDataSelectPro(
      "enterprise/purchase/admin/purchaseType/list",
      {},
      "purTypeId",
      "采购类型",
      async (d, obj) => {
        form.val("purchasePlanFormContent", {
          postName: "",
          auditor: ""
        });
        $("#auditor").empty();
        if (obj) {
          form.val("purchasePlanFormContent", {
            postName: obj.stations
          });
          await admin.initDataSelectPro("user/admin/user/list", { postId: obj.stationsId }, "auditor", "订单审核人", null, "nickname");
        }
        form.render("select");
      },
      "purchaseTypeName"
    );
    await admin.initDataSelectPro("enterprise/purchase/admin/purchaseUrgency/list", {}, "purchaseUrgencyId", "紧急程度", null, "purchaseUrgencyName");
    laydate.render({
      elem: "#planOnTime",
      type: "datetime"
    });

    const tableVal = table.render({
      elem: "#purchasePlanFormTable",
      page: false,
      limit: 999999,
      height: 400,
      data: [],
      cols: [
        [
          { type: "numbers", title: "序号" },
          { field: "skuCode", align: "center", title: "产品SKU编号" },
          { field: "specifications", align: "center", title: "规格号" },
          { field: "productName", align: "center", title: "产品名称" },
          { field: "productCategoryName", align: "center", title: "产品类型" },

          { field: "haveQuantity", align: "center", title: "当前库存数" },
          { field: "mainUnitName", align: "center", title: "主单位" },
          {
            field: "price",
            align: "center",
            title: "最新成本"
          },
          {
            field: "purchaseNumber",
            align: "center",
            title: "需求数量",
            templet: admin.setTableInput("purchaseNumber", ["audit", "detail"].includes(nowData.eventName))
          },
          {
            field: "remark",
            align: "center",
            title: "备注",
            templet: admin.setTableInput("remark", ["audit", "detail"].includes(nowData.eventName))
          },
          {
            align: "center",
            toolbar: "#purchasePlanFormTableBar",
            title: "操作",
            width: 100,
            hide: ["audit", "detail"].includes(nowData.eventName)
          }
        ]
      ],
      done: function () {
        admin.tableInputChange("purchasePlanFormTable");
      }
    });
    if (data && data.id) {
      await admin.initDataSelectPro("user/admin/user/list", { postId: data.postId }, "auditor", "订单审核人", null, "nickname");
      table.reload("purchasePlanFormTable", {
        data: data.planInfoList
      });
      form.val("purchasePlanFormContent", data);
    } else {
      const user = config.getUser();
      form.val("purchasePlanFormContent", {
        creatorName: user.nickname,
        departmentId: user.departmentId
      });
    }

    form.on("submit(inquiryOrderInformationSubmit)", function (d) {
      let formData = { ...d.field };
      formData.planInfoList = table.cache["purchasePlanFormTable"];
      if (nowData.eventName == "add") {
        admin.req(
          "enterprise/purchase/admin/purchasePlan/add",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("purchasePlanTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      } else if (nowData.eventName == "edit") {
        admin.req(
          "enterprise/purchase/admin/purchasePlan/update",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("purchasePlanTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "PUT",
          false,
          "application/json"
        );
      }
      return false;
    });
    $("#purchasePlanSuccess").click(() => {
      const formData = nowData.data;
      formData.planInfoList = table.cache["purchasePlanFormTable"];
      formData.status = "success";
      formData.reason = $("#reason").val();

      admin.req(
        "enterprise/purchase/admin/purchasePlan/audit",
        JSON.stringify(formData),
        function (data) {
          layer.closeAll("loading");
          if (data.code == 200) {
            layer.msg(data.msg, { icon: 1, time: 500 });
            table.reload("purchasePlanTable");
            layer.closeAll("page");
          } else {
            layer.msg(data.msg, { icon: 2, time: 1000 });
          }
        },
        "POST",
        false,
        "application/json"
      );
    });
    $("#purchasePlanFail").click(() => {
      const formData = nowData.data;
      formData.planInfoList = table.cache["purchasePlanFormTable"];
      formData.status = "fail";
      formData.reason = $("#reason").val();
      admin.req(
        "enterprise/purchase/admin/purchasePlan/audit",
        JSON.stringify(formData),
        function (data) {
          layer.closeAll("loading");
          if (data.code == 200) {
            layer.msg(data.msg, { icon: 1, time: 500 });
            table.reload("purchasePlanTable");
            layer.closeAll("page");
          } else {
            layer.msg(data.msg, { icon: 2, time: 1000 });
          }
        },
        "POST",
        false,
        "application/json"
      );
    });
    table.on("tool(purchasePlanFormTable)", function (obj) {
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (obj.tr) {
        obj.tr.on("click", function (e) {
          e.preventDefault(); // 防止默认行为
        });
      }
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["purchasePlanFormTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("purchasePlanFormTable", {
          data: list
        });
      }
    });
    $("#Configure").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "50px",
        title: "配置物料信息",
        path: "components/purchase/skuTableForm.html",
        success: function () {
          parentData.cacheList = [...table.cache["purchasePlanFormTable"]];
          parentData.materialNatureList = ["1"];
          console.log(parentData.cacheList);
          if (parentData.cacheList.length > 0) {
            parentData.notInListIds = table.cache["purchasePlanFormTable"]
              .map((v) => {
                // if (v.id) return v.id
                if (v.productDetailId) return v.productDetailId;
              })
              .join(",");
          } else {
            parentData.notInListIds = "";
          }
        },
        end: function () {
          if (childData.list) {
            const newData = childData.list || [];
            newData.forEach((v) => {
              v.specifications = v.skuSpec;
              v.productName = v.skuName;
              v.productCategory = v.productTypeId;
              v.productCategoryName = v.productTypeName;
              v.unitName = v.mainUnitName;
              v.price = v.currentCostPrice;
              v.remark = '';
            });
            const oldData = table.cache["purchasePlanFormTable"];
            const list = [...oldData, ...newData];
            table.reload("purchasePlanFormTable", {
              data: list // 设置新的数据
            });
          }
        }
      });
    });
  });
</script>

<style>
  #purchasePlanFormContent .layui-form-label {
    width: 110px;
  }

  #purchasePlanFormContent .layui-input-block {
    margin-left: 140px;
  }

  #purchasePlanFormContent .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
